#!/usr/bin/env python
# encoding: utf-8

from app.views.webapi import route_api
from  flask import request,jsonify,g,session
import requests,json
import random

from app import db
from app.model import User

from app.common.libs.Logging import logger
from app.common.libs.UserService import UserService
from app.common.libs.AliyunSmsService import AliyunSmsService
from app.common.libs.Helper import getCurrentDate


@route_api.route("/user/login",methods = [ "GET","POST" ])
def login():
    resp = { 'code':20000,'data':{}}
    req = request.values
    username = req['username'] if 'username' in req else ''
    password = req['password'] if 'password' in req else ''
    if not username:
        resp['code'] = -1
        resp['message'] = "请填写用户名~"
        return jsonify(resp)
    if not password:
        resp['code'] = -1
        resp['message'] = "请填写密码~"
        return jsonify(resp)

    user_info = User.query.filter_by( login_name = username ).first()
    if not user_info:
        resp['code'] = -1
        resp['message'] = "用户未注册~"
        return jsonify(resp)

    # 校验密码是否正确
    if not user_info.login_pwd == UserService.genePwd(password,user_info.login_salt):
        resp['code'] = -1
        resp['message'] = "用户名或密码错误~"
        return jsonify(resp)

    if not user_info.roles:
        resp['code'] = -1
        resp['message'] = "等待管理员审核,审核后获取相应权限~"
        return jsonify(resp)


    token = "%s#%s" % (UserService.geneAuthCode(user_info), user_info.id)
    resp['data'] = {'token': token}
    return jsonify( resp )

@route_api.route("/user/register",methods = [ "GET","POST" ])
def register():
    resp = { 'code':20000 ,'message':'注册成功~','data':{} }
    req = request.values
    username = req['username'] if 'username' in req else ''
    password = req['password'] if 'password' in req else ''
    code = req['code'] if 'code' in req else ''

    if not username:
        resp['code'] = -1
        resp['message'] = "请填写用户名~"
        return jsonify(resp)
    if not password:
        resp['code'] = -1
        resp['message'] = "请填写密码~"
        return jsonify(resp)
    if not code:
        resp['code'] = -1
        resp['message'] = "请输入验证码~"
        return jsonify(resp)
    try:
        if code != session['code']:
            resp['code'] = -1
            resp['message'] = "验证码错误~"
            return jsonify(resp)
    except:
        resp['code'] = -1
        resp['message'] = "验证码错误~"
        return jsonify(resp)

    user_info = User.query.filter_by( login_name = username ).first()
    if user_info:
        resp['code'] = -1
        resp['message'] = "用户名:%s 已注册~"%username
        return jsonify(resp)

    model_user = User()
    model_user.nickname = UserService.geneUserNickname()
    model_user.avatar = 'https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif'
    model_user.login_name = username
    model_user.status = 1
    model_user.login_salt = UserService.geneSalt()
    model_user.login_pwd = UserService.genePwd(password, model_user.login_salt)
    model_user.updated_time = model_user.created_time = getCurrentDate()
    db.session.add(model_user)
    db.session.commit()
    return jsonify( resp )

@route_api.route("/user/password/modify",methods = [ "GET","POST" ])
def passwordModify():
    resp = { 'code':20000 ,'message':'注册成功~','data':{} }
    req = request.values
    username = req['username'] if 'username' in req else ''
    password = req['password'] if 'password' in req else ''
    code = req['code'] if 'code' in req else ''

    if not username:
        resp['code'] = -1
        resp['message'] = "请填写用户名~"
        return jsonify(resp)
    if not password:
        resp['code'] = -1
        resp['message'] = "请填写密码~"
        return jsonify(resp)
    if not code:
        resp['code'] = -1
        resp['message'] = "请输入验证码~"
        return jsonify(resp)
    try:
        if code != session['code']:
            resp['code'] = -1
            resp['message'] = "验证码错误~"
            return jsonify(resp)
    except:
        resp['code'] = -1
        resp['message'] = "验证码错误~"
        return jsonify(resp)

    user_info = User.query.filter_by( login_name = username ).first()
    if not user_info:
        resp['code'] = -1
        resp['message'] = "用户名:%s 未注册, 无法修改~"%username
        return jsonify(resp)

    user_info.login_salt = UserService.geneSalt()
    user_info.login_pwd = UserService.genePwd(password, user_info.login_salt)
    user_info.updated_time = getCurrentDate()

    db.session.commit()
    return jsonify( resp )

@route_api.route("/user/info",methods = [ "GET","POST" ])
def info():
    resp = { 'code':20000,'data':{}}
    req = request.values
    token = req['token'] if 'token' in req else ''
    if not token:
        resp['code'] = -1
        resp['message'] = "need token~"
        return jsonify(resp)

    auth_info = token.split("#")
    if len(auth_info) != 2:
        resp['code'] = -1
        resp['message'] = "token err~"
        return jsonify(resp)
    try:
        user_info = User.query.filter_by(id=auth_info[1]).first()
    except Exception:
        resp['code'] = -1
        resp['message'] = "token err~"
        return jsonify(resp)

    if auth_info[0] != UserService.geneAuthCode( user_info ):
        resp['code'] = -1
        resp['message'] = "token err~"
        return jsonify(resp)

    resp['data'] = {"roles": user_info.roles.split(';'),
                    "introduction":user_info.introduction,
                    "avatar": user_info.avatar,
                    "name": user_info.nickname}

    return jsonify( resp )

@route_api.route("/user/getCode",methods = [ "GET","POST" ])
def getCode():
    resp = { 'code':20000,'data':{},'message':'发送成功'}
    req = request.values
    mobile = req['mobile'] if 'mobile' in req else ''
    if not mobile:
        resp['code'] = -1
        resp['message'] = "请填写电话号码~"
        return jsonify(resp)
    code = '%s'%random.randint(1000,9999)
    res = AliyunSmsService.sendSms(mobile,code)
    if res["Code"] == 'OK':
        session['code'] = code
        resp['message'] = '验证码发送成功~'
    else:
        resp['code'] = -1
        resp['message'] = res['Message']

    return jsonify( resp )


@route_api.route("/user/logout",methods = [ "GET","POST" ])
def logout():
    resp = { 'code':20000,'data':{}}
    return jsonify( resp )

@route_api.route("/user/list",methods = [ "GET","POST" ])
def userList():
    resp = { 'code':20000,'data':{}}
    user_list = User.query.filter_by( status=1 ).all()

    data = []
    for user in user_list:
        roles = user.roles.split(';') if user.roles else []
        data.append({
            "name": user.nickname,
            "roles": roles,
            "login_name": user.login_name
        })
    resp['data'] = data

    return jsonify( resp )

@route_api.route("/user/role/modify",methods = [ "GET","POST" ])
def userRoleModify():
    resp = { 'code':20000,'message':'修改成功~~','data':{}}

    req = request.values
    login_name = req['login_name'] if 'login_name' in req else ''
    roles = req['roles'] if 'roles' in req else []

    items = []
    if roles:
        items = json.loads(roles)

    user_info = User.query.filter_by(login_name=login_name).first()

    if not user_info:
        resp['code'] = -1
        resp['message'] = "用户不存在"
        return jsonify( resp )

    user_info.roles = ';'.join(items)
    db.session.commit()

    return jsonify( resp )

